package com.company.project.service.impl;

import com.company.project.core.IdCardGenerator;
import com.company.project.core.Page;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.StudentDao;
import com.company.project.model.Professional;
import com.company.project.model.Student;
import com.company.project.model.SysUser;
import com.company.project.service.StudentService;
import com.company.project.service.SysUserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
 * Description:
 *
 * @author:
 * Date: 2020-04-02
 * Time: 15:59
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    StudentDao studentDao;
    @Autowired
    SysUserService userService;


    @Transactional
    @Override
    public Result upload(MultipartFile file) {
        try {
            boolean notNull = false;
            InputStream is = file.getInputStream();
            Workbook wb = null;
            boolean isExcel2003 = true;
            String fileName = file.getOriginalFilename();
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);
            if(sheet!=null){
                notNull = true;
            }
//            学院分类
            Set<String> collegeSet = new HashSet<>();
//            专业分类
            Set<String> professionSet = new HashSet<>();
            List<Professional> professionalList = new ArrayList<>();

            Set<String> classSet = new HashSet<>();
            IdCardGenerator idCardGenerator = new IdCardGenerator();
            List<Student> studentList = new ArrayList<>();
            for (int r = 1; r < sheet.getLastRowNum()-1; r++) {
                Row row = sheet.getRow(r);
                if (row == null){
                    continue;
                }

                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);//设置读取转String类型
                row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);

//                所在学院
                String college = row.getCell(0).getStringCellValue();
//                层次
                String level = row.getCell(1).getStringCellValue();
//                班级名称
                String className = row.getCell(2).getStringCellValue();
//                学号
                String studentCode = row.getCell(3).getStringCellValue();
//                学生姓名
                String studentName = row.getCell(4).getStringCellValue();
//                性别
                String gender = row.getCell(5).getStringCellValue();
//                专业名称
                String professional = row.getCell(6).getStringCellValue();
//                外语分级班
                String foreignClass = row.getCell(7).getStringCellValue();
//语种
                String foreignLanguages = row.getCell(8).getStringCellValue();
//层次简称
                String levelCode = row.getCell(10).getStringCellValue();
//学制
                Integer educationYear = Integer.parseInt(row.getCell(11).getStringCellValue());
//专业简称
                String professionalCode = row.getCell(12).getStringCellValue();
//入学年级
                String inGrade = row.getCell(14).getStringCellValue();
//现年级
                String nowGrade = row.getCell(15).getStringCellValue();
//                专业年级
                String professionalGrade = row.getCell(16).getStringCellValue();
//毕业年份
                String graduationYear = row.getCell(18).getStringCellValue();

                String province = row.getCell(19).getStringCellValue();

                if (collegeSet.isEmpty() || !collegeSet.contains(college)){
                    collegeSet.add(college);
                }

                if (professionSet.isEmpty() || !professionSet.contains(professional)){
                    professionSet.add(professional);
                    Professional professionalEntity = new Professional();
                    professionalEntity.setProfessionalCode(professionalCode);
                    professionalEntity.setProfessionalName(professional);
                    professionalEntity.setCollege(college);
                    professionalList.add(professionalEntity);
                }

                Student student = new Student();
                student.setStudentCode(studentCode);
                student.setStudentName(studentName);
                student.setEducationYear(educationYear);
                student.setIdCard(idCardGenerator.generate());
                student.setClassName(className);
                student.setCollege(college);
                student.setForeignClass(foreignClass);
                student.setGender(gender);
                student.setForeignLanguages(foreignLanguages);
                student.setInGrade(inGrade);
                student.setLevel(level);
                student.setLevelCode(levelCode);
                student.setNowGrade(nowGrade);
                student.setGraduationYear(graduationYear);
                student.setProfessionalGrade(professionalGrade);
                student.setProvince(province);
                student.setProfessional(professional);
                student.setProfessionalCode(professionalCode);
                studentList.add(student);
//                两百条数据保存一次
                if(studentList.size()%200 == 0){
                    Result Result = batchSaveStudent(studentList);
                    if (ResultGenerator.isSuccess(Result)){
                        studentList = new ArrayList<>();
                    }
                }
        }
//            保存剩余未保存的
            Result Result = batchSaveStudent(studentList);
            if (ResultGenerator.isSuccess(Result)){
                batchSaveCollege(collegeSet);
                batchSaveProfessional(professionalList);
            }
            return Result;
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult();
        }
    }

    @Override
    public Result batchSaveStudent(List<Student> studentList) {
        try {
            studentDao.batchSaveStudent(studentList);
            return ResultGenerator.genSuccessResult();
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult();
        }
    }

    @Override
    public Result batchSaveCollege(Set<String> collegeSet) {
        try {
            studentDao.batchSaveCollege(collegeSet);
            return ResultGenerator.genSuccessResult();
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult();
        }
    }

    @Override
    public Result batchSaveProfessional(List<Professional> professionalList) {
        try {
            System.out.println(professionalList);
            if (!professionalList.isEmpty()){
                studentDao.batchSaveProfessional(professionalList);
            }
            return ResultGenerator.genSuccessResult();
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult();
        }
    }

    /**
     * 查询学生列表-分页
     *
     * @param studentName  学生名称
     * @param college      学院名称
     * @param professional 专业名称
     * @param pageInfo     分页信息
     * @return
     */
    @Override
    public Result queryStudentPage(String studentName, String college
            , String professional,Integer status, Page pageInfo) {
        Integer count = studentDao.countByCondition(studentName, college,professional,status);
        pageInfo.setAllRow(count);
        List<Student> studentList  = studentDao.selectByCondition(studentName, college,professional,status, pageInfo.getStart(), pageInfo.getSize());
        return ResultGenerator.genSuccessResult(studentList);
    }

    @Override
    public Result getStaticByAge() {
        List<HashMap<String, Object>> staticByAge = studentDao.getStaticByAge();
        return getStatic(staticByAge);
    }

    @Override
    public Result getStaticByProvince() {
        List<HashMap<String, Object>> staticByProvince = studentDao.getStaticByProvince();

        return getStatic(staticByProvince);
    }

    @Override
    public Result getStaticByGender() {
        List<HashMap<String, Object>> staticByGender = studentDao.getStaticByGender();
        return getStatic(staticByGender);
    }

    @Override
    public Result getStaticByNation() {
        List<HashMap<String, Object>> staticByNation = studentDao.getStaticByNation();
        return getStatic(staticByNation);
    }

    private Result getStatic(List<HashMap<String, Object>> dataList){
        List<String> legend  = new ArrayList<>();
        List<HashMap<String,Object>> result = new ArrayList<>();
        for (HashMap<String, Object> map : dataList) {
            String name = map.get("name").toString();
            Integer count = Integer.parseInt(map.get("count").toString());
            HashMap<String,Object> newMap = new HashMap<>();
            newMap.put("name",name);
            newMap.put("value",count);
            result.add(newMap);
            if (legend.isEmpty() || !legend.contains(name)){
                legend.add(name);
            }
        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("legend",legend);
        data.put("result",result);
        return ResultGenerator.genSuccessResult(data);
    }


}
